import datetime
import random

from flask import Flask, session
from flask_sqlalchemy import SQLAlchemy
from redis import StrictRedis
from flask_wtf.csrf import CSRFProtect
from flask_session import Session
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from config import Config
from info import create_app, db, models
from info.models import User

'''
步骤：
    1.初始化
    2.将配置比如数据库等配置文件都写在Config类中
    3.添加数据库
    4.添加redis
    5.添加csrf保护
    6.添加session 并且存储在redis中
    7.添加命令行操作
    8.添加数据库迁移
    9.拆config配置文件
    10.拆功能加载内容
    11.拆路由变成蓝图
    12.添加日志系统
'''
# 去接受创建出来的app
app = create_app('dev')  # db=SQLAlchemy(app)
# from info.models import *
# 7.通过命令行操作
'''
命令行操作表步骤
1.python manager.py db init  创建migrations文件（帮助管理数据库表）
2.python manage.py db migrate -m 'init'  创建一个版本号或者是将数据库表结构创建到versions
3.python manage.py db upgrade 将 versions的结构创建到数据库中
'''
manager = Manager(app)
# 8.添加数据库迁移
Migrate(app, db)
# 添加一条命令
manager.add_command('db', MigrateCommand)


# 添加一万人
def add_test_users():
    users = []
    now = datetime.datetime.now()
    for num in range(0, 10000):
        try:
            user = User()
            user.nick_name = "%011d" % num
            user.mobile = "%011d" % num
            user.password_hash = "pbkdf2:sha256:50000$SgZPAbEj$a253b9220b7a916e03bf27119d401c48ff4a1c81d7e00644e0aaf6f3a8c55829"
            user.last_login = now - datetime.timedelta(seconds=random.randint(0, 2678400))
            users.append(user)
            print(user.mobile)
        except Exception as e:
            print(e)
    with app.app_context():
        db.session.add_all(users)
        db.session.commit()
    print('OK')


if __name__ == '__main__':
    manager.run()
    # add_test_users()
